package com.t11.consumer.service.impl;

import com.t11.common.pojo.LzwGoods;
import com.t11.common.service.GoodsService;
import com.t11.consumer.mapper.GoodsMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class GoodsServiceImpl implements GoodsService {


    @Resource
    GoodsMapper goodsMapper;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public LzwGoods findGoodsById(String goodsId) {
        String key = "seckill:stock:" + goodsId;
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        // 第一次进秒杀详情页单独查找秒杀库存并存到redis作预占库存
        if (opsForValue.get(key) == null) {
            // 如果redis没有该id的预占库存就添加
            Integer stock = findStockById(goodsId);
            opsForValue.set(key, stock);
        }

        return goodsMapper.findGoods(goodsId);
    }

    @Override
    public Integer findStockById(String goodsId) {
        return goodsMapper.findStock(goodsId);
    }
}
